package com.way.app;

import java.util.ArrayList;
import java.util.List;

import android.content.AsyncQueryHandler;
import android.content.ContentResolver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.ContactsContract;

import com.way.bean.ContactBean;
import com.way.service.MAsyncTask;

public class MyApplication extends android.app.Application {

	private List<ContactBean> contactBeanList;
	private AsyncQueryHandler asyncQuery;

	public List<ContactBean> getContactBeanList() {
		return contactBeanList;
	}

	public void setContactBeanList(List<ContactBean> contactBeanList) {
		this.contactBeanList = contactBeanList;
	}

	public void onCreate() {

		// Intent startService = new Intent(MyApplication.this,
		// T9Service.class);
		// startService(startService);
		asyncQuery = new MyAsyncQueryHandler(getContentResolver());
		initSQL();
	}

	protected void initSQL() {
		Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
		String[] projection = { ContactsContract.CommonDataKinds.Phone._ID,
				ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
				ContactsContract.CommonDataKinds.Phone.DATA1, "sort_key",
				ContactsContract.CommonDataKinds.Phone.CONTACT_ID, };
		asyncQuery.startQuery(0, null, uri, projection, null, null,
				"sort_key COLLATE LOCALIZED asc");
	}

	private class MyAsyncQueryHandler extends AsyncQueryHandler {
		public MyAsyncQueryHandler(ContentResolver cr) {
			super(cr);
		}

		protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
			querying(cursor);
		}
	}

	private void querying(final Cursor cursor) {

		Handler handlerInsertOrder = new Handler() {
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case MAsyncTask.DOWNLOADING_START_MESSAGE:
					System.out.println("begin to sort out t9");
					break;
				case MAsyncTask.DOWNLOAD_END_MESSAGE:
					Bundle bundle1 = msg.getData();
					ArrayList<ContactBean> list = (ArrayList<ContactBean>) bundle1
							.get("完成");
					System.out.println(list.size());
					setContactBeanList(list);
					// for(ContactInfo ci : list){
					// System.out.println(ci.getName());
					// System.out.println(ci.getPhoneNum());
					// System.out.println(ci.getFormattedNumber());
					// System.out.println(ci.getPinyin());
					// System.out.println("--------------------------------");
					// }
					break;
				default:
					break;
				}
				super.handleMessage(msg);
			}
		};

		MAsyncTask.startRequestServerData(MyApplication.this,
				handlerInsertOrder, cursor);
	}
}
